package com.lc.sms;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author
 * 网易云信短信核心类
 * @version 1.0
 */
@Slf4j
@Component("cloudFengSms")
public class CloudFengSms {
	    private static String app_key="5lXlCulYRqYUdvj0ZX7AbguRuhN0TfRm" ;
	    private static String app_secret="1eb62a3485060a99b21a702b1ab8f14c" ;
	     
	    
	    
	    /**
	     * @params content 短信内容，【江苏东交】[2018-08-02 05:55:29](监管预警)G206线半程至神山段改建工程-天元路桥一分部天元路桥1分部1%23沥青拌和站(2018-08-02 05:54:51):油石比实际5.08%25理论4.6%25误差0.48%25(高4.25~4.95)
		 * @params mobiles 手机号码 '123,123'
		 * @params missionNums 任务工单号 '20180912161857vVWJ0U,20180912161900fl9KLN'
	     * @params batchNum 批次号 20180912161857caNHjDId 随机生成，不能重复
	     * @return
	     */
	    public static Map<String, String>  sendSms(String mobiles,String content){
	    	String [] mobileArray= mobiles.split(",");
	    	SimpleDateFormat sdf2 =  new SimpleDateFormat("yyyyMMddHHmmss");
	    	String missionNums = null;
	    	for(int i =0;i<mobileArray.length;i++){
	    		if(i==0){
	    			missionNums = sdf2.format(new Date()) + CharSequenceBuilder.createRandomCharSEQ(6);
	    		}else{
	    			missionNums += ","+sdf2.format(new Date()) + CharSequenceBuilder.createRandomCharSEQ(6);
	    		}
	    	}
	    	String batchNum = sdf2.format(new Date()) + CharSequenceBuilder.createRandomCharSEQ(8);
	    	Map<String, String> rtnMap = new HashMap<String, String>();
	    	rtnMap.put("flag", "false");
	    	rtnMap.put("msg", "");
	    	rtnMap.put("code", "");
	    	String Content;
			try {
				Content = java.net.URLEncoder.encode(content, "UTF-8");
				String url = "http://api.zhuanxinyun.com/api/v2/sendSms.json?appKey="+app_key+"&appSecret="+app_secret+"&phones="+mobiles+"&missionNums="+missionNums+"&content="+Content+"&batchNum="+batchNum;
				String str = sendPost(url,"");//post发送
				JSONObject jsonObj = JSONObject.parseObject(str);
		        String code = jsonObj.getString("errorCode");
		        String msg = jsonObj.getString("errorMsg");
				if("提交成功".equals(msg)){
					rtnMap.put("flag", "true");
				}
				rtnMap.put("code", code);
			    rtnMap.put("msg",msg);
			} catch (UnsupportedEncodingException e) {
				
			}
			return rtnMap;
	    }

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url 发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param)
	{
		PrintWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		try
		{
			String urlNameString = url;
			log.info("sendPost - {}", urlNameString);
			URL realUrl = new URL(urlNameString);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("contentType", "utf-8");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null)
			{
				result.append(line);
			}
			log.info("recv - {}", result);
		}
		catch (ConnectException e)
		{
			log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
		}
		catch (SocketTimeoutException e)
		{
			log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
		}
		catch (IOException e)
		{
			log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
		}
		catch (Exception e)
		{
			log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
		}
		finally
		{
			try
			{
				if (out != null)
				{
					out.close();
				}
				if (in != null)
				{
					in.close();
				}
			}
			catch (IOException ex)
			{
				log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
			}
		}
		return result.toString();
	}
	    
	    
	
}
